package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsTreeNodeConstant;
import cc.rengu.igas.bsps.common.constant.DubboMethodConstant;
import cc.rengu.igas.bsps.common.dao.BspsManagerInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsMerGroupInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsRegionInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsManagerInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsMerGroupMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsRegionInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.ManagerInfo;
import cc.rengu.igas.bsps.common.entity.MchntApplyInfo;
import cc.rengu.igas.bsps.common.entity.MerGroupInfo;
import cc.rengu.igas.bsps.common.entity.RegionInfo;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.wechat.facade.base.Header;
import cc.rengu.igas.channel.wechat.facade.request.MchntApplyRemindMsgPushRequest;
import cc.rengu.igas.channel.wechat.facade.response.MchntApplyRemindMsgPushResponse;
import cc.rengu.igas.channel.wechat.facade.result.Result;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.List;

/**
 * 商户入驻异步推送拓展经理
 *
 * @author zhangxuran （联调修改）
 * @version 1.0
 * @date 2020.03.08
 */
public class MchntApplyPushToManagerService extends RadpService {

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String applyId = "";
        try {
            MchntApplyInfo mchntApplyInfo = (MchntApplyInfo) xmlTreeUtil.getXmlTreeObjectValue(BspsTreeNodeConstant.MCHNT_APPLY_INFO, MchntApplyInfo.class);
            applyId = mchntApplyInfo.getApplyId();
            BspsManagerInfoMapper bspsManagerInfoMapper = new BspsManagerInfoMapperImpl();
            List<ManagerInfo> managerInfoList = bspsManagerInfoMapper.selectBspsManagerInfoByAdminArea(mchntApplyInfo.getInstId(), mchntApplyInfo.getProvince(), mchntApplyInfo.getCity(), mchntApplyInfo.getArea());
            if (CollectionUtils.isEmpty(managerInfoList)) {
                rglog.info("商户入驻申请单号:<{}>. 查询拓展经理信息为空！", applyId);
                return -1;
            }
            //将地区码转换成具体地区
            String area = getRegionName(mchntApplyInfo.getArea());
            String manageScope = getManageScope(mchntApplyInfo.getManagement());
            MchntApplyRemindMsgPushRequest remindMsgPushRequest = new MchntApplyRemindMsgPushRequest();
            Header wechatHeader = new Header();
            wechatHeader.setInstId(mchntApplyInfo.getInstId());
            wechatHeader.setSrcSysId(AppParamConstant.SYS_ID);
            wechatHeader.setChanlId(ChannelEnum.BSPS.getChannelType());
            wechatHeader.setTransDate(DateUtil.getCurrentDate());
            wechatHeader.setTransTime(DateUtil.getCurrentTime());
            wechatHeader.setVersion("1.0.0");
            wechatHeader.setBizType("00");
            wechatHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
            wechatHeader.setTxnNum("applyremind");
            remindMsgPushRequest.setHeader(wechatHeader);
            remindMsgPushRequest.setMchntName(mchntApplyInfo.getMchntName());
            remindMsgPushRequest.setOpenId(mchntApplyInfo.getOpenId());
            remindMsgPushRequest.setBusiScope(manageScope);
            remindMsgPushRequest.setContactPhoneNo(mchntApplyInfo.getContactPhone());
            remindMsgPushRequest.setLocation(area);
            remindMsgPushRequest.setAddress(mchntApplyInfo.getAddress());
            remindMsgPushRequest.setMchntContact(mchntApplyInfo.getContactName());
            remindMsgPushRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
            JSONObject params = new JSONObject();
            params.put("applyId", applyId);
            remindMsgPushRequest.setUrlParam(Base64.encodeBase64String(params.toJSONString().getBytes()));


            DubboService dubboService = new DubboServiceImpl();
            for (ManagerInfo managerInfo : managerInfoList) {
                if (StringUtil.isEmptyOrNull(managerInfo.getOpenId()) || "OPENID".equals(managerInfo.getOpenId())) {
                    continue;
                }
                remindMsgPushRequest.setOpenId(managerInfo.getOpenId());
                Result<MchntApplyRemindMsgPushResponse> result = (Result<MchntApplyRemindMsgPushResponse>) dubboService.callDubboService(DubboMethodConstant.WECHAT_MSG_PUSH, "mchntApplyRemindMsgPush", remindMsgPushRequest);
                if (null == result || !result.isSuccess() || !RespCodeEnum.TRANS_SUCCESS.getRespCode().equals(result.getResult().getRespCode())) {
                    rglog.error("商户入驻申请推送给该拓展经理失败，商户名：<{}>, 申请单号：<{}>，拓展经理工号：<{}>", mchntApplyInfo.getMchntName(), mchntApplyInfo.getApplyId(), managerInfo.getManagerId());
                }
            }

        } catch (Exception e) {
            rglog.error("商户入驻异步推送拓展经理异常！ 商户入驻申请单号:<{}>. ", applyId);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("异常信息:<{}>", byteArrayOutputStream.toString());
            return -1;
        }

        return 0;
    }

    /**
     * 根据商户组别编码查询商户组别信息
     */
    private String getManageScope(String management) throws Exception {
        BspsMerGroupInfoMapper bspsMerGroupInfoMapper = new BspsMerGroupMapperImpl();
        MerGroupInfo merGroupInfo = bspsMerGroupInfoMapper.selectBspsMerGroupInfoByGroupNo(management);
        if (null == merGroupInfo || StringUtil.isEmptyOrNull(merGroupInfo.getGrpDesc())) {
            rglog.error("获取商户组别信息失败！");
            return "";
        }
        return merGroupInfo.getGrpDesc();
    }

    private String getRegionName(String regionCode) throws Exception {
        BspsRegionInfoMapper bspsRegionInfoMapper = new BspsRegionInfoMapperImpl();
        RegionInfo regionInfo = bspsRegionInfoMapper.selectBspsRegionInfoByPrimaryKey(regionCode);
        if (null == regionInfo) {
            rglog.error("获取行政区域信息失败！");
            return "";
        }
        return regionInfo.getRegionName();
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }
}